package com.mrzhou.mybatis.config;

import com.baomidou.mybatisplus.core.parser.ISqlParserFilter;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.mrzhou.core.tool.yml.YamlPropertySourceFactory;
import com.mrzhou.mybatis.plus.SqlLogInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

/**
 * 数据源的配置及
 * mybatis Plus的配置
 */
@Slf4j
@Configuration
@MapperScan({"com.mrzhou.**.mapper.**"}) // 配置mybatis的扫描路径
@PropertySource(name = "cloud-mybatis-start", value = "classpath:/cloud-mybatis.yml", factory = YamlPropertySourceFactory.class)
public class MybatisPlusConfiguration {

    /**
     * Mybatis-Plus 分页插件的配置
     * @param sqlParserFilter
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor(ObjectProvider<ISqlParserFilter> sqlParserFilter) {
        log.info("Mybatis-Plus的分页插件配置; 在sql执行前自动添加查询参数");
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();

        // TODO 这里租户相关的MybatisPlus配置去除，目前本项目暂不实现此功能
        // 创建租户解析器, 在查询是自动添加上以tenant_id为条件的sql语句
//        TenantSqlParser tenantSqlParser = new TenantSqlParser();
//        tenantSqlParser.setTenantHandler(new CustomTenantHandler());

//        List<ISqlParser> sqlList = new ArrayList<>();
//        sqlList.add(tenantSqlParser);
//        paginationInterceptor.setSqlParserList(sqlList);
        paginationInterceptor.setSqlParserFilter(sqlParserFilter.getIfAvailable());
        return paginationInterceptor;
    }

    @Bean
    @ConditionalOnProperty(prefix = "mybatis.log", value = "enable", havingValue = "true", matchIfMissing = true)
    public SqlLogInterceptor sqlLogInterceptor() {
        return new SqlLogInterceptor();
    }

//    @Bean
//    public ISqlInjector sqlInjector() {
//        return new CloudSqlInjector();
//    }

}
